import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { upload } from '@/services/api/common'

/**
 * 菜品图片上传组合函数
 * 提供统一的图片上传功能，可在添加和编辑菜品组件中复用
 */
export function useDishImageUpload() {
  // 文件输入引用
  const fileInputRef = ref<HTMLInputElement | null>(null)

  // 触发文件上传
  const triggerUpload = () => {
    if (fileInputRef.value) {
      fileInputRef.value.click()
    }
  }

  // 处理文件变更
  const handleFileChange = async (event: Event, onUploadSuccess?: (imageUrl: string) => void) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]

    if (file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        ElMessage.error('只能上传图片文件!')
        resetFileInput(target)
        return
      }

      // 检查文件大小
      if (file.size > 2 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过 2MB!')
        resetFileInput(target)
        return
      }

      try {
        const res = await upload(file)
        const imageUrl = res.data
        onUploadSuccess?.(imageUrl)
        ElMessage.success('图片上传成功')
      } catch (error) {
        ElMessage.error('图片上传失败')
      } finally {
        resetFileInput(target)
      }
    }
  }

  // 重置文件输入框
  const resetFileInput = (target: HTMLInputElement) => {
    target.value = ''
  }

  return {
    fileInputRef,
    triggerUpload,
    handleFileChange,
    resetFileInput
  }
}